package com.shenghua.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.util.DruidPasswordCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * druid数据库连接池
 * Created by Administrator on 2019/6/5.
 */
@Configuration
public class DruidDBConfig {
    private static Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);

    @Value("${druid-url}")
    private String dbUrl;

    @Value("${druid-username}")
    private String username;

    @Value("${druid-password}")
    private String password;

    @Value("${druid-driverClassName}")
    private String driverClassName;

    @Value("${druid-initialSize}")
    private int initialSize;

    @Value("${druid-minIdle}")
    private int minIdle;

    @Value("${druid-maxActive}")
    private int maxActive;

    @Value("${druid-maxWait}")
    private int maxWait;

    @Value("${druid-timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${druid-minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${druid-validationQuery}")
    private String validationQuery;

    @Value("${druid-testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${druid-testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${druid-testOnReturn}")
    private boolean testOnReturn;

    @Value("${druid-poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${druid-maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${druid-filters}")
    private String filters;

    @Value("${druid-connectionProperties}")
    private String connectionProperties;

    @Value("${druid-passwordCallback}")
    private String passwordCallback;

    @Bean
    public ServletRegistrationBean druidServlet() {
        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单
        servletRegistrationBean.addInitParameter("allow", "");
        // IP黑名单(共同存在时，deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "");
        servletRegistrationBean.addInitParameter("loginPassword", "");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中，首先使用被标注的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setPasswordCallbackClassName(passwordCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter : {0}", e);
        }
        datasource.setConnectionProperties(connectionProperties);
        logger.info("druid 创建连接成功！");
        return datasource;
    }
}
